package cn.sxgan.gen.utils;

import cn.sxgan.gen.exception.ApiException;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

@Component
public class ZipUtil {
    
    /**
     * 压缩指定目录到 ZIP 文件
     *
     * @param sourceDir 待压缩目录路径（必须存在）
     * @param targetZip 目标 ZIP 文件路径（如不存在会自动创建）
     * @throws IOException 压缩失败时抛出异常
     */
    public static void compressToZip(String sourceDir, String targetZip) throws IOException {
        Path sourcePath = Paths.get(sourceDir);
        Assert.isTrue(Files.exists(sourcePath) && Files.isDirectory(sourcePath),
                "源路径必须为有效目录: " + sourceDir);
        String parent = new File(targetZip).getParent();
        Path path = Paths.get(parent);
        if (!Files.exists(path)) {
            Files.createDirectories(path);
        }
        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(targetZip))) {
            compressDirectory(sourcePath, sourcePath, zos);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ApiException("压缩失败");
        }
    }
    
    // 递归压缩目录
    private static void compressDirectory(Path rootDir, Path currentDir, ZipOutputStream zos) throws IOException {
        for (File file : currentDir.toFile().listFiles()) {
            Path filePath = file.toPath();
            String relativePath = rootDir.relativize(filePath).toString().replace("\\", "/");
            
            if (file.isDirectory()) {
                // 添加目录条目
                zos.putNextEntry(new ZipEntry(relativePath + "/"));
                zos.closeEntry();
                // 递归处理子目录
                compressDirectory(rootDir, filePath, zos);
            } else {
                // 添加文件条目
                ZipEntry entry = new ZipEntry(relativePath);
                zos.putNextEntry(entry);
                Files.copy(filePath, zos);
                zos.closeEntry();
            }
        }
    }
    
    /**
     * 解压 ZIP 文件到指定目录
     *
     * @param zipFile   ZIP 文件路径
     * @param outputDir 解压目标目录（如不存在会自动创建）
     * @throws IOException 解压失败时抛出异常
     */
    public static void decompressZip(String zipFile, String outputDir) throws IOException {
        Path destDir = Paths.get(outputDir);
        if (!Files.exists(destDir)) {
            Files.createDirectories(destDir);
        }
        
        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile))) {
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                Path filePath = destDir.resolve(entry.getName());
                // 防御路径遍历攻击（Zip Slip）
                if (!filePath.normalize().startsWith(destDir.normalize())) {
                    throw new IOException("非法路径: " + entry.getName());
                }
                
                if (entry.isDirectory()) {
                    Files.createDirectories(filePath);
                } else {
                    Files.createDirectories(filePath.getParent());
                    Files.copy(zis, filePath, StandardCopyOption.REPLACE_EXISTING);
                }
                zis.closeEntry();
            }
        }
    }
}